<template>
  <div class="xss-protection-example">
    <h2>XSS防护示例</h2>
    
    <!-- 使用XSS防护指令 -->
    <div class="example-section">
      <h3>使用XSS防护指令</h3>
      <div v-xss-safe="unsafeContent"></div>
      <div v-xss-text="unsafeText"></div>
    </div>
    
    <!-- 使用XSS防护函数 -->
    <div class="example-section">
      <h3>使用XSS防护函数</h3>
      <div class="content" v-html="sanitizedContent"></div>
      <div class="text">{{ sanitizedText }}</div>
    </div>
    
    <!-- 输入表单示例 -->
    <div class="example-section">
      <h3>用户输入处理</h3>
      <el-input
        v-model="userInput"
        type="textarea"
        placeholder="输入一些内容（尝试输入HTML或JavaScript代码）"
        :rows="4"
      />
      <div class="output">
        <h4>清理后的内容：</h4>
        <div v-html="processedInput"></div>
      </div>
    </div>
    
    <!-- XSS检测示例 -->
    <div class="example-section">
      <h3>XSS检测</h3>
      <el-input
        v-model="testInput"
        placeholder="输入内容检测是否包含XSS"
      />
      <div class="detection-result">
        <el-alert
          v-if="testInput"
          :title="detectionResult"
          :type="hasXss ? 'error' : 'success'"
          :closable="false"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { sanitizeHtml, sanitizeText, containsPotentialXss } from '../utils/xss'

// 不安全的示例内容
const unsafeContent = '<script>alert("XSS")</script><p onclick="alert('XSS')">点击我</p><a href="javascript:alert('XSS')">恶意链接</a><p>正常内容</p>'
const unsafeText = '<script>alert("XSS")</script>正常文本'

// 用户输入
const userInput = ref('')
const testInput = ref('')

// 计算属性：清理后的内容
const sanitizedContent = computed(() => {
  return sanitizeHtml(unsafeContent)
})

const sanitizedText = computed(() => {
  return sanitizeText(unsafeText)
})

const processedInput = computed(() => {
  return sanitizeHtml(userInput.value)
})

// XSS检测结果
const hasXss = computed(() => {
  return containsPotentialXss(testInput.value)
})

const detectionResult = computed(() => {
  if (!testInput.value) return ''
  return hasXss.value 
    ? '检测到潜在的XSS攻击代码！' 
    : '未检测到XSS攻击代码，内容安全。'
})
</script>

<style scoped>
.xss-protection-example {
  padding: 20px;
}

.example-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.example-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.text {
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
}

.output {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.output h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #606266;
}

.detection-result {
  margin-top: 15px;
}
</style>